<template>
  <h4 class="lighter">
    <i class="ace-icon fa fa-hand-o-right icon-animated-hand-pointer blue"></i>
    <router-link to="/business/course" class="pink"> {{course.name}} </router-link>：
    <i class="ace-icon fa fa-hand-o-right icon-animated-hand-pointer blue"></i>
    <router-link to="/business/chapter" class="pink"> {{chapter.name}} </router-link>
  </h4>
  <hr>
  <p>
    <button @click="add" class="btn btn-white btn-default">
      <i class="ace-icon fa fa-edit"></i>
      新增
    </button>
    &nbsp;
    <button @click="refresh" class="btn btn-white btn-default">
      <i class="ace-icon fa fa-undo"></i>
      刷新
    </button>
  </p>
  <table id="simple-table" class="table  table-bordered table-hover">
    <thead>
    <tr>
      <th>id</th>
      <th>标题</th>
      <th>VOD</th>
      <th>时长</th>
      <th>收费</th>
      <th>顺序</th>
      <th>操作</th>
    </tr>
    </thead>

    <tbody>
    <tr v-for="section in sections" :key="section.id">
        <td>{{ section.id }}</td>
        <td>{{ section.title }}</td>
        <td>{{ section.vod }}</td>
        <td>{{ formatSecond(section.time) }}</td>
        <td>{{ optionKV(section.charge) }}</td>
        <td>{{ section.sort }}</td>
      <td>
        <div class="hidden-sm hidden-xs btn-group">

          <button @click="play(section)" class="btn btn-xs btn-info">
            <i class="ace-icon fa fa-video-camera bigger-120"></i>
          </button>

          <button @click="edit(section)" class="btn btn-xs btn-info">
            <i class="ace-icon fa fa-pencil bigger-120"></i>
          </button>

          <button @click="del(section.id)" class="btn btn-xs btn-danger">
            <i class="ace-icon fa fa-trash-o bigger-120"></i>
          </button>
        </div>

        <div class="hidden-md hidden-lg">
          <div class="inline pos-rel">
            <button class="btn btn-minier btn-primary dropdown-toggle" data-toggle="dropdown" data-position="auto">
              <i class="ace-icon fa fa-cog icon-only bigger-110"></i>
            </button>

            <ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
              <li>
                <a href="#" class="tooltip-info" data-rel="tooltip" title="View">
																			<span class="blue">
																				<i class="ace-icon fa fa-search-plus bigger-120"></i>
																			</span>
                </a>
              </li>

              <li>
                <a href="#" class="tooltip-success" data-rel="tooltip" title="Edit">
																			<span class="green">
																				<i class="ace-icon fa fa-pencil-square-o bigger-120"></i>
																			</span>
                </a>
              </li>

              <li>
                <a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
																			<span class="red">
																				<i class="ace-icon fa fa-trash-o bigger-120"></i>
																			</span>
                </a>
              </li>
            </ul>
          </div>
        </div>
      </td>
    </tr>
    </tbody>
  </table>
  <!-- 分页插件 -->
  <pagination ref="paginationRef" :list="getSectionList" />

  <!-- Modal -->
  <div class="modal fade" id="form-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">表单</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">标题</label>
                <div class="col-sm-10">
                  <input v-model="section.title" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">课程</label>
                <div class="col-sm-10">
                  <input v-model="course.name" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">大章</label>
                <div class="col-sm-10">
                  <input v-model="chapter.name" type="text" class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">视频</label>
                <div class="col-sm-10">
                  <vod
                      :suffixs="['mp4']"
                      text="上传vod文件"
                      :afterUpload="afterUpload"
                      :input-id="'video-upload'"
                      :use="FILE_TYPE.COURSE.key">
                  </vod>
                  <!-- 视频预览 -->
                  <div v-show="section.video" class="row">
                    <div class="col-md-12">
                      <player player-id="form-player-div" ref="playerRef"></player>
                      <video class="hidden" :src="section.video" controls="controls" id="video"></video>
                    </div>
                  </div>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">视频地址</label>
                <div class="col-sm-10">
                  <input v-model="section.video" type="text" disabled class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">VOD ID</label>
                <div class="col-sm-10">
                  <input v-model="section.vod" type="text" disabled class="form-control">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">收费</label>
                <div class="col-sm-10">
                  <select v-model="section.charge" class="form-control">
                    <option v-for="o in CHARGERef" :value="o.key">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">顺序</label>
                <div class="col-sm-10">
                  <input v-model="section.sort" type="text" class="form-control">
                </div>
              </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button @click="saveSection" type="button" class="btn btn-primary">保存</button>
        </div>
      </div>
    </div>
  </div>
  <!-- 视频播放-->
  <modal-player ref="modalPlayer"></modal-player>
</template>

<script>
import axios from "axios";
import {onMounted, ref} from "vue";
import pagination from "@/components/pagination";
import Filter from "@/filter/filter"
import {useRouter} from "vue-router";
import vod from "@/components/vod";
import player from "@/components/player";
import ModalPlayer from "@/components/modal-player";

export default {
  name: "Section",
  components: {
    ModalPlayer,
    pagination,
    vod,
    player
  },
  setup() {
    // sections 数组
    const sections = ref([]);
    const section = ref({}); // 保存小节表单
    const paginationRef = ref(null);
    const router = useRouter();

    // sessionStorage 中存在的值
    const course = ref({});
    const chapter = ref({});

    const FILE_TYPE = FILE_USE;

    const playerRef = ref(); // 阿里云播放器
    const modalPlayer = ref(); // 视频播放模态框

    // 收费枚举
    //const CHARGE = [{ key: 'C', value: '1收费' },{ key: 'F', value: '1免费' }]
    const CHARGERef = ref();
    // 刷新
    const refresh = () => {
      getSectionList(1);
    }

    // 获取小节列表
    const getSectionList = (page) => {
      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/section/list",
          {
            page: page,
            size: paginationRef.value.size,
            courseId: course.value.id,
            chapterId: chapter.value.id
          }
      ).then((response) => {
        Loading.hide();
        const resp = response.data;
        sections.value = resp.content.list;
        paginationRef.value.render(page, resp.content.total);
      })
    }

    // 保存小节
    const saveSection = () => {
      section.value.courseId = course.value.id;
      section.value.chapterId = chapter.value.id;
      section.value.video = '';

      // 保存参数校验
      if ( 1 != 1
                || !Validator.require(section.value.title, "标题")
                || !Validator.length(section.value.title, "标题", 1, 50)
                || !Validator.length(section.value.video, "视频", 1, 200)
        )
      {
        return;
      }

      Loading.show();
      console.log(section)
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/section/save", section.value).then((response) => {
        const resp = response.data;
        if (resp.success) {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.success("保存成功");
          getSectionList(1);
        } else {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.warning(resp.message);
        }
      })
    }

    // 删除小节
    const del = (id) => {
      Confirm.show("删除后不可恢复，确认删除？", function () {
        Loading.show();
        axios.delete(process.env.VUE_APP_SERVER + "/business/admin/section/delete/" + id).then((response) => {
          const resp = response.data;
          if (resp.success) {
            //$('#form-modal').modal('hide');
            getSectionList(1);
          }
        })
        Toast.success("删除成功");
      })
    }

    // 添加小节
    const add = () => {
      section.value = {};
      $('#form-modal').modal('show');
    }

    // 修改小节
    const edit = (param) => {
      // 方法一
      //section.value = JSON.parse(JSON.stringify(param));
      // 方法二
      section.value = $.extend({}, param);
      $('#form-modal').modal('show');
    }

    // 渲染收费字段 c=收费 f=免费
    const optionKV = (key) => {
      return Filter.optionKV(CHARGERef.value, key);
    }

    /**
     * 秒 的格式化 00:00:00
     * @param second
     */
    const formatSecond = (second) => {
      return Filter.formatSecond(second);
    }

    /**
     * 视频上传成功回调
     * @param file
     */
    const afterUpload = (file) => {
      section.value.video = file.path; // 视频路径
      section.value.vod = file.vod;   // vod id 视频点播视频id
      // 获取视频时长
      getVideoTime();
      playerRef.value.playVod(file.vod);
    }

    /**
     * 视频时长
     */
    const getVideoTime = () => {
      setTimeout(() => {
        let e = document.querySelector('#video');
        section.value.time = parseInt(e.duration); // 视频时长 秒
      }, 700);
    }

    /**
     * 播放视频
     */
    const play = (param) => {
      console.log(param)
      modalPlayer.value.playVod(param.vod);
    }

    // 初始加载第一页
    onMounted(() => {
      // 把sessionStorage中的课程 大章取出来（跳转 需求）
      const session_course = SessionStorage.get(SESSION_KEY_COURSE) || {};
      const session_chapter = SessionStorage.get(SESSION_KEY_CHAPTER) || {};
      if (Tool.isEmpty(session_chapter)) {
        router.push("/welcome");
      }
      course.value = session_course;
      chapter.value = session_chapter;

      getSectionList(1);
      CHARGERef.value = SECTION_CHARGE
    })

    return {
      sections,
      refresh,
      paginationRef,
      getSectionList,
      add,
      saveSection,
      section,
      edit,
      del,
      CHARGERef,
      optionKV,
      course,
      chapter,
      formatSecond,
      FILE_TYPE,
      afterUpload,
      playerRef,
      modalPlayer,
      play
    }
  }
}
</script>

<style scoped>
video {
  width: 100%;
}
</style>